<template>
  <div style="background-color: #efefef;height:100vh;">
    <div>
      <button class="goBack" @click="goBack">
        <van-icon name="arrow-left" />
      </button>
      <div class="shpcar">
        购物车
      </div>
      <div class="edit">编辑</div>
    </div>
    <!-- 购物车内容 -->
    <div v-for="store in stores" :key="store.storeName" class="caritem">
      <div>
        <input type="checkbox" v-model="store.selected" @change="shopchoice(store)" />
        <span class="storename">{{ store.storeName }}</span>
      </div>
      <van-swipe-cell v-for="item in store.items" :key="item.id" class="goods-item">
        <div style="display: flex; align-items: center;">
          <input type="checkbox" v-model="item.selected" />
          <van-card :num="item.num" :price="item.price" :title="item.title" :thumb="item.thumb" class="goodscard" />
          <div class="desc">
            <div v-for="(value, key) in item.desc" :key="key">
              {{ key }}: {{ value }}
            </div>
          </div>
        </div>
        <template #right>
          <van-button square text="删除" type="danger" class="delete-button" @click="deleteItem(item)" />
        </template>
      </van-swipe-cell>
    </div>

    <!-- 结算栏 -->
    <div class="checkout-bar" v-if="stores.length > 0">
      <label class="select-all">
        <input type="checkbox" v-model="selectAll" @click="handleCheckAllClick" />
        全选 ({{ stores.length }})
      </label>
      <div style="display: flex;align-items: center;width: 40%;justify-content: space-between;">
        <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
        <van-button type="primary" @click="checkout" size="small"
          style="border-radius: 20rem;border: none;width: 60rem;">结算</van-button>
      </div>
    </div>

    <!-- 购物车为空 -->
    <div v-else>
      <div style="overflow: hidden; position: relative;">
        <van-image width="100%" height="100%" style="margin-top: -35rem;"
          src="https://s10.mogucdn.com/mlcdn/c45406/180704_3ac3b297lghla2jjdhe23d5jfgddf_1500x1170.png" />
        <div class="shpcarwrap">
          <div class="shpcarlist">你的购物车空空如也</div>
          <van-button type="primary" size="small" color="#ff5777" style="width: 80%;border-radius:5rem"
            to="/">去逛逛</van-button>
        </div>
      </div>
      <div>
        <div style="
    margin: 10rem;
    font-size: 14rem;
    color: #5b5858;
">大家都在看</div>
        <van-image width="70%" height="70%" style="margin-top: 60rem;margin-left: 58rem;"
          src="https://s10.mogucdn.com/mlcdn/c45406/180522_7hi685l4939dk3h7cfbcgi178ga5e_514x320.png" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router';
import { Icon as VanIcon, Toast } from 'vant';
// import { CarItem } from '../api/index'
import { watch, ref, computed, onMounted } from 'vue'; // 导入 onMounted 钩子
// 使用 Vue 3 的 <script setup> 语法糖
const router = useRouter(); // 使用 useRouter 钩子
// 步进器
const value = ref(1);
const goBack = () => {
  router.go(-1); // 使用 router 对象的 go 方法返回上一页
};


import { useGwcStore } from '../stores/gwc';
const gwcStore = useGwcStore();
// 商品数据，假设从 API 获取
// 使用计算属性从 Pinia store 获取购物车数据
const stores = computed(() => {
  return gwcStore.groupCartItemsByStore();
});
// 在组件中
onMounted(() => {
  gwcStore.loadFromLocalStorage();
});
const selectAll = ref(false);// 全选状态
// 店铺选择逻辑
const toggleStoreSelection = (store) => {
  store.selected = !store.selected;
  store.items.forEach(item => item.selected = store.selected);
  updateSelectAll();
};
const updateSelectAll = () => {
  selectAll.value = stores.value.every(store => store.selected);
};
const shopchoice = (store) => {
  store.selected = !store.selected;
  toggleStoreSelection(store);
};
// 计算总价的计算属性
const totalPrice = computed(() => {
  return stores.value.flatMap(store => store.items)
    .filter(item => item.selected)
    .reduce((sum, item) => sum + item.price * item.num, 0);
});

// 切换全选状态的方法
const toggleSelectAll = () => {
  selectAll.value = !selectAll.value;
  stores.value.forEach(store => {
    store.selected = selectAll.value;
    store.items.forEach(item => item.selected = selectAll.value);
  });
};
const handleCheckAllClick = () => {
  console.log('全选复选框被点击');
  toggleSelectAll();
};

const deleteItem = (item) => {
  gwcStore.removeProductFromCart(item.id); // 调用 Pinia store 中的方法删除商品
  Toast('商品已删除');
};
// 结算的方法
const checkout = () => {
  if (!stores.value.some(store => store.items.some(item => item.selected))) {
    Toast('请选择要结算的商品');
    return;
  }

  // 构建订单确认页面需要的商品信息
  const selectedItems = stores.value.flatMap(store => store.items);

  // 将商品信息和图片信息一起编码
  const itemsString = JSON.stringify(selectedItems);
  const encodedItems = encodeURIComponent(itemsString);
  localStorage.setItem('selectedItems', itemsString);
  router.push({ path: 'orderCon', query: { items: encodedItems } });
  console.log(encodedItems);

};
// 在组件加载时发送请求并初始化全选状态
watch(() => stores.value.flatMap(store => store.items.map(item => item.selected)), (newSelectedStatus) => {
  selectAll.value = newSelectedStatus.every(status => status);
}, { deep: true });

</script>

<style lang="less" scoped>
.goBack {
  position: absolute;
  top: 15px;
  /* 调整为合适的像素值 */
  left: 20px;
  /* 调整为合适的像素值 */
  background-color: rgba(255, 255, 255, 0);
  border: none;
  font-size: 14px;
  /* 调整为合适的像素值 */
}

.shpcar {
  width: 100%;
  height: 44rem;
  text-align: center;
  font-size: 20rem;
  line-height: 44rem;
  border-bottom: 1rem solid #d1cdcd;
  color: #6f6f6f;
  background-color: white;
}

.edit {
  position: absolute;
  right: 20rem;
  top: 10rem;
  color: #6f6f6f;
}

.desc {
  position: absolute;
  left: 127rem;
  font-size: 12rem;
  color: #999;
  top: 52rem;
  display: flex;
  width: 230rem;
  flex-wrap: wrap;

  div {
    padding: 0 5rem;
  }
}

.shpcarwrap {
  position: absolute;
  bottom: 22px;
  left: 33%;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
}

.shpcarlist {
  color: #686767;
  font-size: 12rem;
  padding: 10rem;
}

.caritem {
  background-color: #ffffff;
  height: auto;
  width: 93%;
  margin-left: 13rem;
  box-sizing: border-box;
  margin-top: 10rem;
  padding: 10rem 0;
  border-radius: 15rem;

  .storename {
    margin-left: 15rem;
    font-weight: bold;
  }

  .spxx {
    width: 70%;
    height: 100%;
    bacckground-color: #ffffff;
    position: absolute;
    top: 0;
    right: 0;

    .spbt {
      font-weight: bold;
      font-size: 14rem;
    }

    .spjs {
      font-size: 12rem;
      background-color: #f7f7f7;
    }

    .spjg {
      color: red;
      font-weight: bold;
      font-size: 18rem;
    }
  }
}

.goods-card {
  margin: 0;
  background-color: rgb(255, 255, 255);
  height: 100rem;
}

.delete-button {
  height: 100%;
}

.checkout-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.select-all {
  display: flex;
  align-items: center;
}

.total-price {
  color: #ff5777;
  font-size: 18px;
}

.van-button {
  background-color: #ff5777;
  color: #fff;
}
</style>
